﻿package com.pay;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;

import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import cn.zf.http.HttpClientUtil;

import com.itrus.util.sign.RSAWithSoftware;
import com.jfinal.core.Controller;
import com.pay.dinpay.client.serivce.DinpayService;
import com.pay.yeepay.client.service.YeepayService;
import com.pay.yeepay.client.service.yeepayTimer;
import com.pay.yeepay.server.Configuration;
import com.tool.CryptTool;
import com.vo.Gateway;
import com.vo.Order;
import com.vo.OrdersNew;
import com.vo.Person;
import com.vo.PersonGateway;
import com.vo.System_interface;

public class hdpay extends Controller {

	public void node() {
		try {
			getRequest().setCharacterEncoding("utf-8");
			// 获取支付请求信息
			String bank_code_1 = getPara("bank_code_1"); // 银行直连代码
			String client_ip_2 = getPara("client_ip_2"); // 客户ip
			String input_charset_3 = getPara("input_charset_3"); // 参数编码格式
			String merchant_code_4 = getPara("merchant_code_4"); // 商家号
			String notify_url_5 = getPara("notify_url_5"); // 服务器异步通知地址
			String order_amount_6 = getPara("order_amount_6"); // 商户订单金额
			String order_no_7 = getPara("order_no_7"); // 商户订单号
			String order_time_8 = getPara("order_time_8"); // 商户订单时间
			String pay_type_9 = getPara("pay_type_9"); // 支付类型
			String product_name_10 = getPara("product_name_10"); // 商品名称
			String return_url_11 = getPara("return_url_11")==null?getPara("notify_url_5"):getPara("return_url_11"); // 页面跳转同步通知地址
			String hmac = getPara("hmac"); // 签名信息
			
			Person per = null;
			if (!("").equals(merchant_code_4)) {
				per = Person.dao.findById(Integer.parseInt(merchant_code_4));
			}
			if (per == null) {
				renderHtml("抱歉，无该用户！");
			} else if ("".equals(order_amount_6)) {
				renderHtml("抱歉，交易金额太小。");
			} else if ("".equals(order_no_7) || "".equals(order_time_8)
					|| "".equals(product_name_10) || "".equals(hmac)
					|| "".equals(return_url_11) || "".equals(notify_url_5)) {
				renderHtml("抱歉，参数提交错误！");
			} else if (per.getInt("ifnet") == 2) {
				renderHtml("抱歉，您的网银接口未开通请联系客服进行开通!");
			} else {
				OrdersNew order = new OrdersNew();
				order.set("client_ip_2", client_ip_2); // client_ip_2 用户IP 用来验签
				order.set("rem1", CryptTool.getIpAddr(getRequest())); // 商户IP 存入数据库
				order.set("input_charset_3", input_charset_3);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
				String orderid = "O" + sdf.format(new Date())
						+ CryptTool.getPasswordOfNumber(2) + merchant_code_4;
				order.set("orderid", orderid); // 新订单号
				order.set("merchant_code_4", merchant_code_4);
				order.set("order_no_7", order_no_7);
				// 金额精度控制为2，丢弃后面的小数位 start
				BigDecimal order_amountD = null;
				try{
					order_amountD = new BigDecimal(order_amount_6)
							.setScale(2,BigDecimal.ROUND_FLOOR);
				}catch(Exception e){
					renderHtml("抱歉，金额提交错误！");
				}
				order.set("order_amount_6", order_amountD);
				// 金额精度控制为2，丢弃后面的小数位 end
				order.set("product_name_10", product_name_10);
				order.set("bank_code_1", bank_code_1);
				order.set("notify_url_5", notify_url_5);
				order.set("order_time_8", order_time_8);
				order.set("pay_type_9", pay_type_9);
				order.set("return_url_11", return_url_11);
				order.set("hmac", hmac);

				boolean boo = YeepayService.service.order(order);
				if (boo) {
					PersonGateway pergetGateway = PersonGateway.dao
							.findById(per.getInt("id"));
					Gateway gateway = Gateway.dao.findById(pergetGateway
							.getInt("gateway_id"));

					merchant_code_4 = gateway.getStr("gateway_merid");

					String keyValue = gateway.getStr("gateway_key"); // 商家密钥
					String type = gateway.getStr("gateway_type"); // 加密方式

					int function = gateway.getInt("gateway_function");
					// --------------------------------------------------------
					if (function == 6) {
						dinpay(merchant_code_4, keyValue, type, order);
					} else {
						renderText("系统错误！");
					}
					// --------------------------------------------------------
				} else {
					renderText("抱歉,交易签名无效");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 智付接口
	 * 
	 * @param p1_MerId
	 * @param keyValue
	 * @param order
	 */
	public String dinpayQR(String merchant_code_4, String keyValue, String type, OrdersNew order) {
			String merchant_code = merchant_code_4;	
			String service_type = getPara("pay_type_9");
			String interface_version = "V3.1";	
			String input_charset = "UTF-8";				
			String sign_type = type;
			String orderid = order.getStr("orderid"); // 本系统订单号
			String order_amount_6 = order.getBigDecimal("order_amount_6").toString();
			String product_name_10 = order.getStr("product_name_10");
			String merchant_private_key = keyValue;
			String pay_key = Configuration.getInstance().getValue("pay_key");

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date createtime = order.get("create_time");
			System_interface systemInterface = System_interface.dao.findById(1);
			String httpurl = systemInterface.getStr("system_interface_httpurl");
			Timer timer = new Timer();
			timer.schedule(new yeepayTimer(order.getStr("orderid"), timer),
					15 * 60 * 1000);
			StringBuffer signSrc= new StringBuffer();	
			signSrc.append("client_ip=").append(getPara("client_ip_2")).append("&");	
			signSrc.append("interface_version=").append(interface_version).append("&");
			signSrc.append("merchant_code=").append(merchant_code).append("&");				
			signSrc.append("notify_url=").append(httpurl + "/dinpay/qrNotify").append("&");	
			signSrc.append("order_amount=").append(order_amount_6).append("&");
			signSrc.append("order_no=").append(orderid).append("&");
			signSrc.append("order_time=").append(sdf.format(createtime)).append("&");
			signSrc.append("product_name=").append(product_name_10).append("&");
			signSrc.append("service_type=").append(service_type);		
			
			String signInfo = signSrc.toString();
			String sign = "";
			try {
				sign = RSAWithSoftware.signByPrivateKey(signInfo,merchant_private_key);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			
			
			Map<String, String> reqMap = new HashMap<String, String>();
			reqMap.put("merchant_code", merchant_code_4);
			reqMap.put("interface_version", interface_version);
			reqMap.put("sign", sign);
			reqMap.put("sign_type", sign_type);
			reqMap.put("notify_url", httpurl + "/dinpay/qrNotify");
			reqMap.put("order_no", orderid);
			reqMap.put("order_time", sdf.format(createtime));
			reqMap.put("order_amount", order_amount_6);
			reqMap.put("product_name", product_name_10);
			reqMap.put("service_type", service_type);
			reqMap.put("client_ip", getPara("client_ip_2"));
			
			String yzxmallUrl = Configuration
					.getInstance().getValue("yzxmallUrl"); // 交易请求地址头信息
			String result = new HttpClientUtil().doPost( yzxmallUrl + "/dinpay/qrcode?input_charset=UTF-8", reqMap, "utf-8");
			
			try{
				Document document = DocumentHelper.parseText(result);
				String resp_code = document.selectSingleNode("//dinpay/response/resp_code").getText();	
				String resp_desc = document.selectSingleNode("//dinpay/response/resp_desc").getText();	
				String result_code = document.selectSingleNode("//dinpay/response/result_code").getText();	
			
				if("SUCCESS".equals(resp_code)){
				
						String qrcode = document.selectSingleNode("//dinpay/response/qrcode").getText();	
						order.set("qrcode", qrcode);
						order.set("resp_code", resp_code);
						order.set("resp_desc", resp_desc);
						order.set("result_code", result_code);
						order.update();
					}else{
						order.set("resp_code", resp_code);
						order.set("resp_desc", resp_desc);
						order.set("result_code", result_code);
						order.update();
					}
		
		
				}catch(Exception e){
			}
		
			return result;
	}
	
	/**
	 * 智付接口
	 * 
	 * @param p1_MerId
	 * @param keyValue
	 * @param order
	 */
	public void dinpay(String merchant_code_4, String keyValue, String type, OrdersNew order) {
		if("alipay_scan".equals(getPara("pay_type_9")) 
				|| "weixin_scan".equals(getPara("pay_type_9")) 
				|| "zhb_scan".equals(getPara("pay_type_9")) 
				|| "qq_scan".equals(getPara("pay_type_9"))){
			// PC端扫码支付

			String merchant_code = merchant_code_4;	
			String service_type = getPara("pay_type_9");
			String interface_version = "V3.1";	
			String input_charset = "UTF-8";				
			String sign_type = type;
			String orderid = order.getStr("orderid"); // 本系统订单号
			String order_amount_6 = order.getBigDecimal("order_amount_6").toString();
			String product_name_10 = order.getStr("product_name_10");
//			String bank_code_1 = order.getStr("bank_code_1");
			String merchant_private_key = keyValue;
//			String redo_flag = "1";
			String pay_key = Configuration.getInstance().getValue("pay_key");

			setAttr("merchant_code", merchant_code);
			setAttr("service_type", service_type);
			setAttr("interface_version", interface_version);
//			setAttr("input_charset", input_charset);
			setAttr("sign_type", sign_type);
			setAttr("order_no", orderid);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date createtime = order.get("create_time");
			setAttr("order_time", sdf.format(createtime));
			setAttr("order_amount", order_amount_6);
			setAttr("product_name", product_name_10);
			System_interface systemInterface = System_interface.dao.findById(1);
			String httpurl = systemInterface.getStr("system_interface_httpurl");
			setAttr("client_ip", getPara("client_ip_2"));
			// TODO 回调页面client_ip_2
			setAttr("notify_url", httpurl + "/dinpay/qrNotify");
//			setAttr("return_url", httpurl + "/dinpay/return");
//			String bank_code = DinpayService.service.getDinpayParticipate(bank_code_1);
//			if(null == bank_code){
//				bank_code = "";
//			}		
//			if("null".equals(bank_code)){
//				bank_code = "";
//			}
//			setAttr("bank_code", bank_code);
			setAttr("merchant_private_key", merchant_private_key);
//			setAttr("redo_flag", redo_flag);
			setAttr("pay_key", pay_key);

			PersonGateway pergate = PersonGateway.dao.findById(order.get("merchant_code_4"));
			String title = pergate.get("title");
			if (title == null || title.equals("")) {
				title = "提交中。。。";
			}
			setAttr("title", title);
			String titletime = pergate.get("titletime");
			if (titletime == null || titletime.equals("")) {
				titletime = "1000";
			}
			setAttr("titletime", titletime);
			Timer timer = new Timer();
			timer.schedule(new yeepayTimer(order.getStr("orderid"), timer),
					15 * 60 * 1000);
			renderJsp("/WEB-INF/pay/dinpay/qrcode/qrCode.jsp");			
		}else{
			
			String merchant_code = merchant_code_4;	
			String service_type = "direct_pay";
			String interface_version = "V3.0";	
			String input_charset = "UTF-8";				
			String sign_type = type;
			String orderid = order.getStr("orderid"); // 本系统订单号
			String order_amount_6 = order.getBigDecimal("order_amount_6").toString();
			String product_name_10 = order.getStr("product_name_10");
			String bank_code_1 = order.getStr("bank_code_1");
			String merchant_private_key = keyValue;
			String redo_flag = "1";
			String pay_key = Configuration.getInstance().getValue("pay_key");
	
			setAttr("merchant_code", merchant_code);
			setAttr("service_type", service_type);
			setAttr("interface_version", interface_version);
			setAttr("input_charset", input_charset);
			setAttr("sign_type", sign_type);
			setAttr("order_no", orderid);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date createtime = order.get("create_time");
			setAttr("order_time", sdf.format(createtime));
			setAttr("order_amount", order_amount_6);
			setAttr("product_name", product_name_10);
			System_interface systemInterface = System_interface.dao.findById(1);
			String httpurl = systemInterface.getStr("system_interface_httpurl");
			// TODO 回调页面
			setAttr("notify_url", httpurl + "/dinpay/return");
			setAttr("return_url", httpurl + "/dinpay/return");
			String bank_code = DinpayService.service.getDinpayParticipate(bank_code_1);
			if(null == bank_code){
				bank_code = "";
			}		
			if("null".equals(bank_code)){
				bank_code = "";
			}
			setAttr("bank_code", bank_code);
			setAttr("merchant_private_key", merchant_private_key);
			setAttr("redo_flag", redo_flag);
			setAttr("pay_key", pay_key);
	
			PersonGateway pergate = PersonGateway.dao.findById(order.get("merchant_code_4"));
			String title = pergate.get("title");
			if (title == null || title.equals("")) {
				title = "提交中。。。";
			}
			setAttr("title", title);
			String titletime = pergate.get("titletime");
			if (titletime == null || titletime.equals("")) {
				titletime = "1000";
			}
			setAttr("titletime", titletime);
			Timer timer = new Timer();
			timer.schedule(new yeepayTimer(order.getStr("orderid"), timer),
					15 * 60 * 1000);
			renderJsp("/WEB-INF/pay/dinpay/b2c/bankPay.jsp");
		}
	}

	public void qrResp() {
		try {
			getRequest().setCharacterEncoding("utf-8");
			// 获取支付请求信息
			String result = getPara("result");
			
			Document document = DocumentHelper.parseText(result);
			String resp_code = document.selectSingleNode("//dinpay/response/resp_code").getText();	

			if("SUCCESS".equals(resp_code)){
				String order_no = document.selectSingleNode("//dinpay/response/order_no").getText();	
				OrdersNew order = OrdersNew.dao.findById(order_no);
				if(order == null){
					renderHtml("订单有误！");
					return;
				}
				String resp_desc = document.selectSingleNode("//dinpay/response/resp_desc").getText();	
				String result_code = document.selectSingleNode("//dinpay/response/result_code").getText();	
				try{
					String qrcode = document.selectSingleNode("//dinpay/response/qrcode").getText();	
					order.set("qrcode", qrcode);
					order.set("resp_code", resp_code);
					order.set("resp_desc", resp_desc);
					order.set("result_code", result_code);
					order.update();
				}catch(NullPointerException e){
					order.set("resp_code", resp_code);
					order.set("resp_desc", resp_desc);
					order.set("result_code", result_code);
					order.update();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String queryQRCode() {
		try {
			getRequest().setCharacterEncoding("utf-8");
			// 获取支付请求信息
			String order_no  = getPara("order_no_7");
			OrdersNew order = OrdersNew.dao.findById(order_no);
			if(order == null){
				
				return "{\"code\":0,\"qrcode\":\"正在生成，请耐心等待....\"}";
			}else{
				if("SUCCESS".equals(order.get("resp_code"))){
					return "{\"code\":1,\"qrcode\":\""+order.getStr("qrcode")+"\"}";
				}else{
					return "{code:0;qrcode:'正在生成，请耐心等待....'}";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "{code:0;qrcode:'正在生成，请耐心等待....'}";
	}
	
	
	
	
	public static void main(String[] args) throws DocumentException {
		// 获取支付请求信息
		String result = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><dinpay><response><interface_version>V3.1</interface_version><merchant_code>1111110166</merchant_code><order_amount>0.01</order_amount><order_no>2018020110005534</order_no><order_time>2018-02-01 10:00:55</order_time><qrcode>https://qr.alipay.com/bax06859dtdbjk7fgafq6029</qrcode><resp_code>SUCCESS</resp_code><resp_desc>通讯成功</resp_desc><result_code>0</result_code><sign>MOHQItf96nzAuSU9S/Sum6m8BaNau3uSLdpIaZ5C+RhTf8l9umbfEinhDUUrgyYVRw/yzHsHphI/a/FdL07C4H/60G4RtjiP8bd/VlYYW+1P3K91g79WtaC7JA0kyRJPvGAiHsmlqromdSICnoJe/GykAMGX0wznJHpoukjCl4s=</sign><sign_type>RSA-S</sign_type><trade_no>1660929997</trade_no><trade_time>2018-02-01 10:01:03</trade_time></response></dinpay>";
		
		Document document = DocumentHelper.parseText(result);
		String a = document.selectSingleNode("//dinpay/response/interface_version").getText();	
		System.out.println(a);
	}

	
	public void zfQRnode() {
		String result = "";
		try {
			getRequest().setCharacterEncoding("utf-8");
			// 获取支付请求信息
			String bank_code_1 = getPara("bank_code_1"); // 银行直连代码
			String client_ip_2 = getPara("client_ip_2"); // 客户ip
			String input_charset_3 = getPara("input_charset_3"); // 参数编码格式
			String merchant_code_4 = getPara("merchant_code_4"); // 商家号
			String notify_url_5 = getPara("notify_url_5"); // 服务器异步通知地址
			String order_amount_6 = getPara("order_amount_6"); // 商户订单金额
			String order_no_7 = getPara("order_no_7"); // 商户订单号
			String order_time_8 = getPara("order_time_8"); // 商户订单时间
			String pay_type_9 = getPara("pay_type_9"); // 支付类型
			String product_name_10 = getPara("product_name_10"); // 商品名称
			String return_url_11 = getPara("return_url_11")==null?getPara("notify_url_5"):getPara("return_url_11"); // 页面跳转同步通知地址
			String hmac = getPara("hmac"); // 签名信息
			
			Person per = null;
			if (!("").equals(merchant_code_4)) {
				per = Person.dao.findById(Integer.parseInt(merchant_code_4));
			}
			if (per == null) {
				renderHtml("抱歉，无该用户！");
			} else if ("".equals(order_amount_6)) {
				renderHtml("抱歉，交易金额太小。");
			} else if ("".equals(order_no_7) || "".equals(order_time_8)
					|| "".equals(product_name_10) || "".equals(hmac)
					|| "".equals(return_url_11) || "".equals(notify_url_5)) {
				renderHtml("抱歉，参数提交错误！");
			} else if (per.getInt("ifnet") == 2) {
				renderHtml("抱歉，您的网银接口未开通请联系客服进行开通!");
			} else {
				OrdersNew order = new OrdersNew();
				order.set("client_ip_2", client_ip_2); // client_ip_2 用户IP 用来验签
				order.set("rem1", CryptTool.getIpAddr(getRequest())); // 商户IP 存入数据库
				order.set("input_charset_3", input_charset_3);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
				String orderid = "O" + sdf.format(new Date())
						+ CryptTool.getPasswordOfNumber(2) + merchant_code_4;
				order.set("orderid", orderid); // 新订单号
				order.set("merchant_code_4", merchant_code_4);
				order.set("order_no_7", order_no_7);
				// 金额精度控制为2，丢弃后面的小数位 start
				BigDecimal order_amountD = null;
				try{
					order_amountD = new BigDecimal(order_amount_6)
							.setScale(2,BigDecimal.ROUND_FLOOR);
				}catch(Exception e){
					renderHtml("抱歉，金额提交错误！");
				}
				order.set("order_amount_6", order_amountD);
				// 金额精度控制为2，丢弃后面的小数位 end
				order.set("product_name_10", product_name_10);
				order.set("bank_code_1", bank_code_1);
				order.set("notify_url_5", notify_url_5);
				order.set("order_time_8", order_time_8);
				order.set("pay_type_9", pay_type_9);
				order.set("return_url_11", return_url_11);
				order.set("hmac", hmac);

				boolean boo = YeepayService.service.order(order);
				if (boo) {
					PersonGateway pergetGateway = PersonGateway.dao
							.findById(per.getInt("id"));
					Gateway gateway = Gateway.dao.findById(pergetGateway
							.getInt("gateway_id"));

					merchant_code_4 = gateway.getStr("gateway_merid");

					String keyValue = gateway.getStr("gateway_key"); // 商家密钥
					String type = gateway.getStr("gateway_type"); // 加密方式

					int function = gateway.getInt("gateway_function");
					// --------------------------------------------------------
					if (function == 6) {
						result = dinpayQR(merchant_code_4, keyValue, type, order);
					} else {
						renderText("系统错误！");
					}
					// --------------------------------------------------------
				} else {
					renderText("抱歉,交易签名无效");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		renderText(result);
//		return result;
	}
}
